﻿using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;

namespace HyperWPF
{
    public class UseDataStore
    {

        /// <summary>
        /// 所有的表格值数据
        /// </summary>
        private Dictionary<int, List<string>> data = new();

        /// <summary>
        /// 最大行数 
        /// </summary>
        public int MaxRows { get; } = 1000000;

        /// <summary>
        /// 最大列数
        /// </summary>
        public int MaxColumns { get; } = 65535;

        /// <summary>
        /// 用户设置的行数
        /// </summary>
        private int _usersetrows=1000;
        public int UserSetRows
        {
            get => _usersetrows;
            set
            {
                if (value <= MaxRows)
                {
                    _usersetrows = value;
                }
            }
        }

        /// <summary>
        /// 用户设置的列数
        /// </summary>
        private int _usersetcolumns=100;
        public int UserSetColumns
        {
            get => _usersetcolumns;
            set
            {
                if (value <= MaxColumns)
                {
                    _usersetcolumns = value;
                }
            }
        }



        /// <summary>
        /// 给定的读写锁
        /// </summary>
        private readonly ReaderWriterLockSlim rwLock = new();


        public EventHandler DataChanged;

        public UseDataStore()
        {
            Init();
        }
        public void Init()
        {
            data.Clear();
            if (data.Count == 0)
            {
                for (int i = 0; i < UserSetRows; i++)
                {
                    List<string> list = new List<string>();
                    for (int j = 0; j < UserSetColumns; j++)
                    {
                        list.Add("");
                    }
                    data.Add(i, list);
                }
            }
        }

        public string GetData(int row, int column)
        {
            if (row >= UserSetRows || column >= UserSetColumns)
            {
                return "";
            }
            try
            {
                rwLock.EnterReadLock();
                return data[row][column];
            }
            finally
            {
                rwLock.ExitReadLock();
            }
        }

        public bool SetData(int row, int column, string value)
        {
            if (row >= UserSetRows || column >= UserSetColumns)
            {
                return false;
            }
            try
            {
                rwLock.EnterWriteLock();
                data[row][column] = value;
            }
            finally
            {
                rwLock.ExitWriteLock();
                if (DataChanged != null)
                {
                    DataChanged(new int[] { row, column }, null);
                }
            }
            return true;
        }


    }
}
